<?php
namespace app\admin\controller;

use think\Controller;
use app\common\model\system\SystemAdmin;
use app\common\controller\AdminController;
use think\facade\Env;
use think\captcha\facade\Captcha;
/**
 * Class Login
 * @package app\admin\controller
 */
class Login extends AdminController
{

    /**
     * 初始化方法
     */

    public function initialize() {
        // 用户若已经登录，则重定向到首页
        if($this->isLogin()) {
            return $this->redirectTo(__url('index/index'));
        }
    }

    /**
     * 生成验证码
     * @return \think\Response
     */
    public function verify()
    {
        return Captcha::create();
    }
    /**
     * 用户登录
     * @return string
     * @throws \Exception
     */
    public function index()
    {

        if ($this->request->isPost()) {
            $post = $this->request->param('data');
            try{
                $rule = [
                    'username|用户名'      => 'require',
                    'password|密码'       => 'require',
                   // 'captcha|验证码'=>'require|captcha'
                ];
                $this->validate($post, $rule);
                $admin = SystemAdmin::where(['username' => $post['username']])->find();
                if (empty($admin)) {
                    throw new \Exception('用户不存在');
                }
                if (password($post['password']) != $admin->password) {
                    throw new \Exception('密码输入有误');
                }
                if ($admin->status == 0) {
                    throw new \Exception('账号已被禁用');
                }
                $admin = $admin->toArray();

                unset($admin['password']);
                $admin['expire_time'] =  time() + 7200;
                session('admin', $admin);
                $data = [
                    'code' => 1,
                    'msg' => '登录成功...',
                ];
                return json($data);

            }catch(\Exception $e){
                $data = [
                    'code' => 0,
                    'msg' => $e->getMessage(),
                ];
                return json($data);
            }



        }

        return view();
    }




}